﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using Gateway.Console.Models;
using Gateway.Console.Services;
using Gateway.Console.Services.Azure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Gateway.Console.Controllers
{
    public class AnalyticsApiController : ApiController
    {
        const string DateStringFormat   = "yyyy-MM-dd";
        private ConsoleContext db = new ConsoleContext();

        // GET api/AnalyticsApi/report
        public IHttpActionResult Get(string id)
        {
            var reportModel = db.AnalyticsReportModels
                .Where(model => model.Report == id)
                .FirstOrDefault();
            if (reportModel == null)
            {
                return NotFound();
            }
            if (!reportModel.HasMultipleSeries)
            {
                return Ok(new[] { reportModel.Rows
                    .OrderBy(row => row.Date)
                    .Select(row => new List<Object> { row.Date.ToString(DateStringFormat), row.Value })});
            }
            else
            {
                var seriesResults = reportModel.Rows
                    .GroupBy(row => row.Series)
                    .OrderBy(series => series.Key)
                    .ToList();
                return Ok(new
                {
                    labels = seriesResults.Select(series => String.IsNullOrWhiteSpace(series.Key) ? "{None}" : series.Key),
                    data = seriesResults
                        .Select(series => series
                            .Select(row => new List<Object> { row.Date.ToString(DateStringFormat), row.Value })),
                });
            }
        }

        [HttpPost]
        public async Task<IHttpActionResult> Post(string id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            switch (id)
            {
                case "aggregate-rollup-weekly":
                    return await DoAnalyticsAction((accessToken, subscriptionId, model) =>
                        HDInsightManagement.InitiateCalculateAggregates(accessToken, subscriptionId, model));

                case "check-weblog-partitions":
                    return await DoAnalyticsAction((accessToken, subscriptionId, model) =>
                        HDInsightManagement.InitiateUpdateIISLogTablePartitions(accessToken, subscriptionId, model));

                default:
                    return NotFound();
            }
        }

        private async Task<IHttpActionResult> DoAnalyticsAction(Action<AuthenticationResult, string, AnalyticsModel> action)
        {
            var model = await db.AnalyticsModel.FirstOrDefaultAsync();
            var deployment = await db.Deployments.FirstOrDefaultAsync();
            if (model == null || deployment == null)
            {
                return BadRequest("No analytics model has been deployed.");
            }
            else if (String.IsNullOrWhiteSpace(model.RefreshToken))
            {
                return BadRequest("Refresh token has not been saved for deployment");
            }
            var accessToken = OAuth2AuthenticationExtensions.GetAccessTokenFromRefreshToken(model.RefreshToken);
            action(accessToken, deployment.SubscriptionSelection, model);
            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}